<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container >
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="成本核算单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="costCode">
              <a-input v-model="model.costCode" :disabled="formDisabled" placeholder="请输入成本核算单号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flowFlag">
              <j-dict-select-tag type="list" v-model="model.flowFlag" :disabled="formDisabled" dictCode="order_cost_flow_type" placeholder="请选择审批流程" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="订单编号" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="schedulingNumber">
              <j-popup
                v-model="model.schedulingNumber"
                field="schedulingNumber"
                org-fields="scheduling_number,review_id,id"
                dest-fields="schedulingNumber,reviewId,orderId"
                code="over_order"
                :multi="false"
                :disabled="formDisabled"
                @input="popupCallback"
                />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="业务员" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="salesman">
              <j-select-user-by-dep-v2 v-model="model.salesman" disabled :multi="true" />
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="6" >
            <a-form-model-item label="客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <a-input v-model="model.customerId" placeholder="请输入客户" disabled></a-input>
            </a-form-model-item>
          </a-col>-->
          <a-col :span="6" >
            <a-form-model-item label="客户名称" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="customerName">
              <a-input v-model="model.customerName" placeholder="请输入客户名称" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="类型" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="customerType">
              <j-dict-select-tag type="list"  dictCode="customer_category" v-model="model.customerType"  disabled placeholder="请选择类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="客户类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerCategory">
              <j-dict-select-tag
                type="list"
                v-model="model.customerCategory"
                dictCode="erp_customer_type,name,id"
                placeholder="请选择客户类别"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="首次下单日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deDate">
              <j-date placeholder="请选择首次下单日期" v-model="model.deDate" style="width: 100%" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" style="margin-top:10px;margin-bottom:10px">
          <j-vxe-table
            keep-source
            :ref="refKeys[0]"
            :loading="crmOrderCostDetailTable.loading"
            :columns="crmOrderCostDetailTable.columns"
            :dataSource="crmOrderCostDetailTable.dataSource"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="false"
            :toolbar="false"
          >
            <template v-slot:exchangeRate="props">
              <span>6.35</span>
            </template>
          </j-vxe-table>
          </a-col>
          <a-col :span="24" >
            <a-form-model-item label="备注" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="notes">
              <a-textarea v-model="model.notes" :disabled="formDisabled" rows="4" placeholder="请输入备注" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->



  </a-spin>
</template>

<script>

import {getAction, postAction} from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'

  export default {
    name: 'CrmOrderCostForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 18 },
        },
        labelCol3: {
          xs: { span: 24 },
          sm: { span: 2 },
        },
        wrapperCol3: {
          xs: { span: 24 },
          sm: { span: 22 },
        },
        model:{
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          flowFlag: [{ required: true, message: '请选择审批流程!' }],
        },
        refKeys: ['crmOrderCostDetail', ],
        tableKeys:['crmOrderCostDetail', ],
        activeKey: 'crmOrderCostDetail',
        // 订单成本核算明细
        crmOrderCostDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料编码',
              key: 'code',
              width:"200px",
            },
            {
              title: '物料名称',
              key: 'name',
              width:"200px",
            },
            {
              title: '规格型号',
              key: 'spec',
              width:"200px",
            },
            {
              title: '件/吨',
              key: 'ton',
              width:"200px",
            },
            {
              title: '原料',
              key: 'material',
              width:"200px",
            },
            {
              title: '包材',
              key: 'packageMaterials',
              width:"200px",
            },
            {
              title: '中间费用',
              key: 'midExpenses',
              width:"200px",
            },
            {
              title: '合计',
              key: 'total',
              width:"200px",
            },
            {
              title: '出厂价',
              key: 'exWorksPrice',
              width:"200px",
            },
            {
              title: '陆运费',
              key: 'landFreight',
              width:"200px",
            },
            {
              title: '海运费',
              key: 'seaFreight',
              width:"200px",
            },
            {
              title: '证书费用',
              key: 'certificate',
              width:"200px",
            },
            {
              title: '版费',
              key: 'royalty',
              width:"200px",
            },
            {
              title: '保费',
              key: 'insurancePremium',
              width:"200px",
            },
            {
              title: '佣金',
              key: 'commission',
              width:"200px",
            },
            {
              title: '其它',
              key: 'other2',
              width:"200px",
            },
            {
              title: '合计',
              key: 'total2',
              width:"200px",
            },
            {
              title: '合同价',
              key: 'contractPrice',
              type: JVXETypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '税前合同价',
              key: 'excludingTaxPrice',
              type: JVXETypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '差价（RMB）',
              key: 'priceDifference',
              type: JVXETypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '汇率',
              key: 'exchangeRate',
              type: JVXETypes.slot,
              align: 'center',
              width:"200px",
              slotName: 'exchangeRate',
            },
            {
              title: '实际中间费用',
              key: 'intermediateCosts',
               type: JVXETypes.inputNumber,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '提成',
              key: 'orderCommission',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '订单数（吨）',
              key: 'ywTon',
              width:"200px",
            },
          ]
        },
        url: {
          add: "/cost/crmOrderCost/add",
          edit: "/cost/crmOrderCost/edit",
          queryById: "/cost/crmOrderCost/queryById",
          crmOrderCostDetail: {
            list: '/cost/crmOrderCost/queryCrmOrderCostDetailByMainId'
          },
          queryByOrderId: "/cost/crmOrderCost/queryByOrderId",
          queryQuote: "/cost/crmOrderCost/queryQuote",
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      customFormData: {
        type: Object,
        default: () => {
          return {}
        },
        required: false,
      },
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      if (this.customFormData != null && this.customFormData.id) {
        this.model = this.customFormData
        this.editAfter() //现在子表内容需要
      }
    },
    methods: {
      getCode() {
        postAction('/sys/fillRule/executeRuleByCode/order_cost_code', {}).then((res) => {
          this.model.costCode = res.result
          this.$forceUpdate()
        })
      },
      addBefore(){
        this.getCode()
        Vue.set(this.model, 'flowFlag', 1)
        this.crmOrderCostDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.crmOrderCostDetail.list, params, this.crmOrderCostDetailTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          crmOrderCostDetailList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      queryByOrderId(){
        getAction(this.url.queryByOrderId,{orderId:this.model.orderId}).then((res)=>{
          if(res.success){
            Vue.set(this.model, 'customerCategory', res.result.customerCategory)
            Vue.set(this.model, 'customerName', res.result.customerName)
            Vue.set(this.model, 'customerType', res.result.customerType)
            Vue.set(this.model, 'customerId', res.result.customerId)
            Vue.set(this.model, 'deDate', res.result.deDate)
            Vue.set(this.model, 'salesman', res.result.salesman)
          }else{
            Vue.set(this.model, 'customerCategory', '')
            Vue.set(this.model, 'customerName','')
            Vue.set(this.model, 'customerType', '')
            Vue.set(this.model, 'customerId', '')
            Vue.set(this.model, 'deDate', '')
            Vue.set(this.model, 'salesman', '')
          }

        })
      },
      queryQuote(){
        getAction(this.url.queryQuote,{reviewId:this.model.reviewId}).then((res)=>{
          if(res.success){
            this.crmOrderCostDetailTable.dataSource = res.result
          }else{
            this.crmOrderCostDetailTable.dataSource = []
          }
        })
      },
     popupCallback(value,row){
      this.model = Object.assign(this.model, row);
      this.queryByOrderId()
      this.queryQuote()
     },

    }
  }
</script>

<style scoped>
</style>